package implicits

import java.io.{File, FilenameFilter}
import java.nio.file.Files
import com.github.tototoshi.csv._
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import utils.Implicits._

import scala.collection.mutable
import scala.collection.JavaConverters._
import implicits.Implicits._

import scala.reflect.ClassTag

/**
 * Created by Administrator on 2019/9/12
 */
trait MyFileTool {

  implicit class MyFile(file: File) {

    def unixPath = {
      val path = file.getAbsolutePath
      path.unixPath
    }

    def lines: List[String] = lines()

    def txtLines = lines.map(_.split("\t").toList)

    def lines(encoding: String = "UTF-8") = FileUtils.readLines(file, encoding).asScala.toList

    def str = FileUtils.readFileToString(file, "UTF-8")

    def allFiles: List[File] = {

      def loop(acc: List[File], files: List[File]): List[File] = {
        files match {
          case Nil => acc
          case x :: xs => x.isDirectory match {
            case false => loop(x :: acc, xs)
            case true => loop(acc, xs ::: x.listFiles().toList)
          }
        }
      }

      loop(List(), List(file))
    }

    def createDirectoryWhenNoExist = {
      if (!file.exists && !file.isDirectory) FileUtils.forceMkdir(file)
      file
    }

    def namePrefix: String = {
      val fileName = file.getName
      fileName.fileNamePrefix
    }

    def deleteQuietly = {
      FileUtils.deleteQuietly(file)
    }

    def toXlsxFile(xlsxFile: File) = {
      val lines = file.lines
      lines.toXlsxFile(xlsxFile)
    }

    def copyTo(destFile: File) = {
      val isLink = Files.isSymbolicLink(file.toPath)
      if (isLink) {
        val truePath = Files.readSymbolicLink(file.toPath)
        Files.createSymbolicLink(destFile.toPath, truePath)
      } else {
        FileUtils.copyFile(file, destFile)
      }
    }

    def fileCopyToDir(destDir: File) = {
      if (Files.isSymbolicLink(file.toPath)) {
        val destFile = new File(destDir, file.getName)
        file.copyTo(destFile)
      } else {
        FileUtils.copyFileToDirectory(file, destDir)
      }
    }

    def dirCopyToDirUnder[X: ClassTag](destDir: File, fileNameFilter: FilenameFilter): Unit = {
      file.listFiles(fileNameFilter).foreach { subFile =>
        val subDestDir = new File(destDir, file.getName).createDirectoryWhenNoExist
        subFile.fileCopyToDir(subDestDir)
      }
    }

    def dirCopyToDirUnder(destDir: File)(implicit fileNameFilter: FilenameFilter): Unit = {
      dirCopyToDirUnder(destDir, fileNameFilter)
    }

    def dirCopyToDir[X: ClassTag](destDir: File, fileNameFilter: FilenameFilter): Unit = {
      file.listFiles(fileNameFilter).foreach { subFile =>
        subFile.fileCopyToDir(destDir)
      }
    }

    def dirCopyToDir(destDir: File)(implicit fileNameFilter: FilenameFilter): Unit = {
      dirCopyToDir(destDir, fileNameFilter)
    }


  }


}
